"use strict";
var gulp = require("gulp");
var babel = require("gulp-babel");
var fs=require("fs");
var plumber = require('gulp-plumber');
var path = require('path');
var less=require("gulp-less");
var destChmod=require("./gulp-dest-chmod");
var webpack=require("gulp-webpack");
var named = require('vinyl-named');

gulp.task("src",function(){
    return gulp.src("src/**/*.js")
        .pipe(plumber())
        .pipe(babel())
        .pipe(destChmod("build"))
        .pipe(gulp.dest("build",{mode:"0555"}));
});

gulp.task("common",function(){
    return gulp.src("common/**/*.js")
        .pipe(plumber())
        .pipe(babel())
        .pipe(destChmod("build/common"))
        .pipe(gulp.dest("build/common",{mode:"0555"}));
});

gulp.task("ejs",function(){
    return gulp.src("views/**/*.ejs")
        .pipe(plumber())
        .pipe(destChmod("build/views"))
        .pipe(gulp.dest("build/views",{mode:"0555"}));
});

gulp.task("js",function(){
    return gulp.src(["views/**/*.js","views/**/*.jsx"])
        .pipe(plumber())
        .pipe(named(function(file){
            var name=file.relative;
            if (name.toLowerCase().endsWith(".js")) name=name.substring(0,name.length-3);
            else if (name.toLowerCase().endsWith(".jsx")) name=name.substring(0,name.length-4);
            return name;
        }))
        .pipe(webpack(require("./webpack.config")))
        .pipe(destChmod("build/views"))
        .pipe(gulp.dest("build/views",{mode:"0555"}));
});


gulp.task("default", ["src","ejs","js","common"]);

gulp.task("watch",["default"], function () {
    gulp.watch("src/**/*.js", ["src"]);
    gulp.watch("common/**/*.js", ["common","js","src"]);
    gulp.watch("views/**/*.ejs", ["ejs"]);
    gulp.watch(["views/**/*.js","views/**/*.jsx"], ["js"]);
});